package com.xiaoxin.suma.fragment;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.NetworkUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.SimpleClickListener;
import com.xiaoxin.suma.R;
import com.xiaoxin.suma.net.ErrUtils;
import com.xiaoxin.suma.utils.RxUtil;
import com.xiaoxin.suma.widget.RecycleViewDivider;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Observable;
import rx.Subscription;

/**
 * A simple {@link Fragment} subclass.
 */
public abstract class BaseRecycleFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {


    public int STATUS = DATA_NO;
    protected BaseQuickAdapter adapter;
    protected LinearLayout emptyView;
    protected TextView tvEmpty;
    protected ImageView ivEmpty;
    protected int page = 0;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerview;
    @BindView(R.id.swRefresh)
    SwipeRefreshLayout swipeRefresh;
    Unbinder unbinder;
    private long start, end;
    private ViewGroup container;
    public static final int NETWORK_ERROR = 0;
    public static final int DATA_ERROR = 1;
    public static final int DATA_NO = 2;
    public static final int DATA_LOAD = 3;

    public BaseRecycleFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        this.container = container;
        View view = inflater.inflate(R.layout.fragment_base_recycle, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initView() {
        super.initView();
        emptyView = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.empty_view, container, false);
        tvEmpty = (TextView) emptyView.findViewById(R.id.tv_empty);
        ivEmpty = (ImageView) emptyView.findViewById(R.id.iv_empty);
        emptyView.setOnClickListener(v -> onRefresh());
        recyclerview.setHasFixedSize(true);
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = getAdapter();
        if (enableLoadMore()) {
            adapter.setOnLoadMoreListener(this, recyclerview);
        }
        swipeRefresh.setOnRefreshListener(this);
        recyclerview.setAdapter(adapter);
        recyclerview.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.line)));
        recyclerview.addOnItemTouchListener(new SimpleClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                BaseRecycleFragment.this.onItemClick(baseQuickAdapter, view, i);
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                BaseRecycleFragment.this.onItemChildClick(adapter, view, position);
            }

            @Override
            public void onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                BaseRecycleFragment.this.onItemChildLongClick(adapter, view, position);
            }

            @Override
            public void onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                BaseRecycleFragment.this.onItemLongClick(adapter, view, position);
            }
        });
    }

    /**
     * 上拉刷新
     */
    @Override
    public void onRefresh() {
        swipeRefresh.setRefreshing(true);
        STATUS = DATA_LOAD;
        page = 0;
        loadData(page);
    }

    /**
     * 是否激活加载更多
     */
    public abstract boolean enableLoadMore();

    /**
     * 下拉加载更多，目前用不到
     */
    @Override
    public void onLoadMoreRequested() {
        loadData(page++);
    }

    public abstract BaseQuickAdapter getAdapter();

    public abstract void onItemClick(BaseQuickAdapter adapter, View view, int position);

    public void onItemLongClick(BaseQuickAdapter adapter, View view, int position) {

    }

    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

    }

    public void onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {

    }

    public void checkData() {
        if (STATUS > DATA_ERROR && adapter.getData().isEmpty()) {
            setStatus(DATA_NO);
        }
    }


    public void handleThrowable(Throwable throwable) {
        if (NetworkUtils.isAvailableByPing()) {
            ErrUtils.pase(throwable);
            setStatus(DATA_ERROR);
        } else {
            setStatus(NETWORK_ERROR);
        }
    }

    /**
     * 数据直接就是list，可以直接用
     */
    public <T> void getDataList(Observable<List<T>> observable) {
        start = System.currentTimeMillis();
        Subscription subscription = observable.compose(RxUtil.rxSchedulerio_main())
                .doOnUnsubscribe(this::checkData)
                .subscribe(this::handleData, this::handleThrowable);
        addSubscription(subscription);
    }

    /**
     * 数据不是list要通过 handleData 方法处理
     */
    public <T> void getDataListOfMap(Observable<T> observable) {
        start = System.currentTimeMillis();
        Subscription subscription = observable.compose(RxUtil.rxSchedulerio_main())
                .doOnUnsubscribe(this::checkData)
                .subscribe(this::handleData, this::handleThrowable);
        addSubscription(subscription);
    }

    public <T> void handleData(List<T> list) {
        adapter.setNewData(list);
    }

    public <T> void handleData(T t) {

    }

    public void setStatus(int status) {
        STATUS = status;
        tvEmpty.setText("");
        switch (STATUS) {
            case NETWORK_ERROR:
                tvEmpty.setText("没有可用的网络");
//                ivEmpty.setImageResource(R.drawable.page_icon_network);
                break;
            case DATA_ERROR:
                tvEmpty.setText("内容加载失败\n点击重新加载");
//                ivEmpty.setImageResource(R.drawable.pagefailed_bg);
                break;
            case DATA_NO:
                ivEmpty.setImageResource(getEmptyView());
                break;
        }
        adapter.setEmptyView(emptyView);
    }

    public int getEmptyView() {
        tvEmpty.setText("暂无数据");
        return R.drawable.data_no;
    }

    public abstract void loadData(int i);


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
